package com.jaydenxiao.common.commonutils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/1/8.
 */

/**
 * 1、dp转换px<br/>
 * 2、px转换dp<br/>
 * 3、设备宽度<br/>
 * 4、设备高度<br/>
 * 5、SD卡判断<br/>
 * 6、网络判断<br/>
 * 7、VersionName<br/>
 * 8、VersionCode<br/>
 * 9、DeviceId<br/>
 * 10、手机品牌<br/>
 * 11、手机型号<br/>
 * 12、系统Android API等级<br/>
 * 13、系统Android 版本<br/>
 * 14、App进程id<br/>
 * 15、App进程Name<br/>
 * 16、创建App缓存文件夹<br/>
 * 17、Uri转换File<br/>
 * 18、获取AndroidManifestxml里meta data的值<br/>
 */
public class DeviceUtil {

   /**
    * dp 转化为 px
    *
    * @param context
    * @param dpValue
    * @return
    */
   public static int dp2px(Context context, float dpValue) {
      final float scale = context.getResources().getDisplayMetrics().density;
      return (int) (dpValue * scale + 0.5f);
   }

   /**
    * px 转化为 dp
    *
    * @param context
    * @param pxValue
    * @return
    */
   public static int px2dp(Context context, float pxValue) {
      final float scale = context.getResources().getDisplayMetrics().density;
      return (int) (pxValue / scale + 0.5f);
   }

   /**
    * 获取设备宽度（px）
    *
    * @param context
    * @return
    */
   public static int deviceWidth(Context context) {
      return context.getResources().getDisplayMetrics().widthPixels;
   }

   /**
    * 获取设备高度（px）
    *
    * @param context
    * @return
    */
   public static int deviceHeight(Context context) {
      return context.getResources().getDisplayMetrics().heightPixels;
   }

   /**
    * SD卡判断
    *
    * @return
    */
   public static boolean isSDCardAvailable() {
      return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
   }

   /**
    * 是否有网
    *
    * @param context
    * @return
    */
   public static boolean isNetworkConnected(Context context) {
      if (context != null) {
         ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                 .getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo mNetworkInfo = mConnectivityManager
                 .getActiveNetworkInfo();
         if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
         }
      }
      return false;
   }

   /**
    * 返回版本名字
    * 对应build.gradle中的versionName
    *
    * @param context
    * @return
    */
   public static String getVersionName(Context context) {
      String versionName = "";
      try {
         PackageManager packageManager = context.getPackageManager();
         PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
         versionName = packInfo.versionName;
      } catch (Exception e) {
         e.printStackTrace();
      }
      return versionName;
   }

   /**
    * 返回版本号
    * 对应build.gradle中的versionCode
    *
    * @param context
    * @return
    */
   public static String getVersionCode(Context context) {
      String versionCode = "";
      try {
         PackageManager packageManager = context.getPackageManager();
         PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
         versionCode = String.valueOf(packInfo.versionCode);
      } catch (Exception e) {
         e.printStackTrace();
      }
      return versionCode;
   }

   /**
    * 获取设备的唯一标识，deviceId
    *
    * @param context
    * @return
    */
   public static String getDeviceId(Context context) {
      TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      String deviceId="-";
      try{
         deviceId = tm.getDeviceId();
      }catch(Exception e){

      }
      return deviceId;
   }

   /**
    * 获取手机品牌
    *
    * @return
    */
   public static String getPhoneBrand() {
      return Build.BRAND;
   }

   /**
    * 获取手机型号
    *
    * @return
    */
   public static String getPhoneModel() {
      return Build.MODEL;
   }

   /**
    * 获取手机Android API等级（22、23 ...）
    *
    * @return
    */
   public static int getBuildLevel() {
      return Build.VERSION.SDK_INT;
   }

   /**
    * 获取手机Android 版本（4.4、5.0、5.1 ...）
    *
    * @return
    */
   public static String getBuildVersion() {
      return Build.VERSION.RELEASE;
   }

   /**
    * 获取当前App进程的id
    *
    * @return
    */
   public static int getAppProcessId() {
      return android.os.Process.myPid();
   }

   /**
    * 获取当前App进程的Name
    *
    * @param context
    * @param processId
    * @return
    */
   public static String getAppProcessName(Context context, int processId) {
      String processName = null;
      ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
      // 获取所有运行App的进程集合
      List l = am.getRunningAppProcesses();
      Iterator i = l.iterator();
      PackageManager pm = context.getPackageManager();
      while (i.hasNext()) {
         ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
         try {
            if (info.pid == processId) {
               CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));

               processName = info.processName;
               return processName;
            }
         } catch (Exception e) {
            Log.e(DeviceUtil.class.getName(), e.getMessage(), e);
         }
      }
      return processName;
   }

   /**
    * 创建App文件夹
    *
    * @param appName
    * @param application
    * @return
    */
   public static String createAPPFolder(String appName, Application application) {
      return createAPPFolder(appName, application, null);
   }

   /**
    * 创建App文件夹
    *
    * @param appName
    * @param application
    * @param folderName
    * @return
    */
   public static String createAPPFolder(String appName, Application application, String folderName) {
      File root = Environment.getExternalStorageDirectory();
      File folder;
      /**
       * 如果存在SD卡
       */
      if (DeviceUtil.isSDCardAvailable() && root != null) {
         folder = new File(root, appName);
         if (!folder.exists()) {
            folder.mkdirs();
         }
      } else {
         /**
          * 不存在SD卡，就放到缓存文件夹内
          */
         root = application.getCacheDir();
         folder = new File(root, appName);
         if (!folder.exists()) {
            folder.mkdirs();
         }
      }
      if (folderName != null) {
         folder = new File(folder, folderName);
         if (!folder.exists()) {
            folder.mkdirs();
         }
      }
      return folder.getAbsolutePath();
   }

   /**
    * 通过Uri找到File
    *
    * @param context
    * @param uri
    * @return
    */
   public static File uri2File(Activity context, Uri uri) {
      File file;
      String[] project = {MediaStore.Images.Media.DATA};
      Cursor actualImageCursor = context.getContentResolver().query(uri, project, null, null, null);
      if (actualImageCursor != null) {
         int actual_image_column_index = actualImageCursor
                 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
         actualImageCursor.moveToFirst();
         String img_path = actualImageCursor
                 .getString(actual_image_column_index);
         file = new File(img_path);
      } else {
         file = new File(uri.getPath());
      }
      if (actualImageCursor != null) actualImageCursor.close();
      return file;
   }

   /**
    * 获取AndroidManifest.xml里 <meta-data>的值
    *
    * @param context
    * @param name
    * @return
    */
   public static String getMetaData(Context context, String name) {
      String value = null;
      try {
         ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
         value = appInfo.metaData.getString(name);
      } catch (PackageManager.NameNotFoundException e) {
         e.printStackTrace();
      }
      return value;
   }

   public static String getDeviceInfo() {
      return "\"" + Build.MODEL + Build.VERSION.CODENAME + Build.MANUFACTURER + "\"";
   }

   public static String getCPUSerial(Context context) {
      String str = "", strCPU = "", cpuAddress = "0000000000000000";
      return cpuAddress;
   }

   /**
    * getUUId
    *
    * @return
    */
   private static final String INSTALLATION = "INSTALLATION";

   public synchronized static String getUUId(Context context) {
      String sID = null;
      File installation = new File(context.getFilesDir(), INSTALLATION);
      try {
         if (!installation.exists()) writeInstallationFile(installation);
         sID = readInstallationFile(installation);
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
      return sID;
   }

   private static void writeInstallationFile(File installation) throws IOException {
      FileOutputStream out = new FileOutputStream(installation);
      String id = UUID.randomUUID().toString();
      out.write(id.getBytes());
      out.close();
   }

   private static String readInstallationFile(File installation) throws IOException {
      RandomAccessFile f = new RandomAccessFile(installation, "r");
      byte[] bytes = new byte[(int) f.length()];
      f.readFully(bytes);
      f.close();
      return new String(bytes);
   }



   /**
    * 判断应用是否已经启动
    * @param context 一个context
    * @param packageName 要判断应用的包名
    * @return boolean
    */
   public static boolean isAppAlive(Context context, String packageName){
      ActivityManager activityManager =
              (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
      List<ActivityManager.RunningAppProcessInfo> processInfos
              = activityManager.getRunningAppProcesses();
      for(int i = 0; i < processInfos.size(); i++){
         if(processInfos.get(i).processName.equals(packageName)){
            Log.i("NotificationLaunch",
                    String.format("the %s is running, isAppAlive return true", packageName));
            return true;
         }
      }
      Log.i("NotificationLaunch",
              String.format("the %s is not running, isAppAlive return false", packageName));
      return false;
   }

}